#!/bin/bash

# 定义一个数组，其中每个元素是一个字符串，格式为 "子目录｜打包后的包名"
directory_pairs=(
    "h5-bjs｜trabjs"
    "h5-block-trade｜trablock"
    "h5-bond｜trabond"
    "h5-bond-stock｜trabtstk"
    "h5-buyback｜trabuybk"
    "h5-ipo｜traipo"
    "h5-magin-credit｜tramcrdt"
    "h5-magin-pubbusi｜trampub"
    "h5-nation-debt｜trandebt"
    "h5-neeq｜traneeq"
    "h5-ofund｜traofund"
    "h5-pubbusi｜trapbusi"
    "h5-stock-hk｜trastkhk"
    "h5-tender-offer｜traoffer"
)


# 提示用户输入
echo "确认是否需要加密加签 (y/n):"

# 读取用户输入
read user_input

# 根据用户输入执行不同的操作
case $user_input in
    y)
        echo "你选择了加签"
        should_security=true
        ;;
    n)
        echo "你选择了不加签"
        should_security=false
        ;;
    *)
        echo "无效的选项,默认不加签"
        should_security=false
        ;;
esac

# 安装所有依赖  
echo "开始安装全局依赖"  
pnpm i  
npm run build

# 如果stream文件夹存在，则删除它  
if [ -d "stream" ]; then  
    rm -rf stream  
fi

# 确保stream目录存在  
echo "creat stream in root directory..."  
mkdir -p stream  

# 定义一个函数来执行 npm run build
function build_and_move {
    local dir_and_new_name=$1
    (
        # 分割字符串，提取目录名和重命名
        IFS='｜' read -r dir new_name <<< "$dir_and_new_name"
                
        if [ ! -d "$dir" ]; then
            echo "Error: Directory $dir does not exist."
            exit 1
        fi

        cd "$dir" || exit 1
        echo "Building in $dir..."
        npm run build
        if [ $? -ne 0 ]; then
            echo "Build failed in $dir."
            exit 1
        fi
        echo "Build in $dir completed."

        # 重命名并移动 dist 文件夹
        if [ -d "dist" ]; then
            target_dir="../stream/$new_name/1.0.0"
            mkdir -p "$target_dir"
            mv dist/* "$target_dir"
            echo "Moved and renamed $dir/dist to stream/$new_name/1.0.0"
        else
            echo "Warning: $dir/dist does not exist."
        fi
    ) &
}

# 启动所有构建任务
pids=()
for pair in "${directory_pairs[@]}"; do
    build_and_move "$pair"
    pids+=($!)
done

# 等待所有构建任务完成
for pid in "${pids[@]}"; do
    wait "$pid"
    if [ $? -ne 0 ]; then
        echo "An error occurred during the build process."
        exit 1
    fi
done

echo "All builds completed and moved successfully total ${#pids[@]}"

# 对所有包进行加密加签操作
function startSecurityAndEncrypt {
    echo "security and encrypt start...$(pwd) "   
    local dir_and_new_name=$1
    (
        # 分割字符串，提取目录名和重命名
        IFS='｜' read -r module_name package_name <<< "$dir_and_new_name"
        
        local dir="stream/$package_name"
       
        # 定义 1.0.0 文件夹的路径
        version_dir="$dir/1.0.0"
        origin_dir="$dir/origin"
        mv $version_dir $origin_dir

        # 检查加解密前的原始文件夹是否存在
        if [ -d "$origin_dir" ]; then
             # 定义输出 ZIP 文件的路径（可以使用项目名称作为部分文件名）
            zip_path="$dir/encrypted_signed.zip"
            # 创建一个唯一的临时解压目录
            temp_dir_path="$dir/unzip_temp"
            # 执行加密加签操作（替换为你的实际命令和参数）
            light security --encrypt --sign -e "$origin_dir" -o "$zip_path"
            # 检查加密加签是否成功（检查 ZIP 文件是否存在）
            if [ -f "$zip_path" ]; then
                # 解压 ZIP 文件到临时目录
                mkdir -p "$temp_dir_path"
                unzip "$zip_path" -d "$temp_dir_path"
                # 移动解压后的 1.0.0 文件夹到原位置
                mv "$temp_dir_path" "$version_dir"
                # 清理临时目录
                rm -rf "$origin_dir"
                rm -rf "$zip_path"
                echo "encrypted_signed $module_name successfully."
            else
                echo "Failed to create encrypted  $module_name"
            fi
        fi
    )
}


#  校验如果打开加密加签，默认不开启
if [ "$should_security" = true ]; then
    # 启动所有加密加签任务
    for pair in "${directory_pairs[@]}"; do
        startSecurityAndEncrypt "$pair"
    done
    echo "package finish with should_security $should_security"
fi 



 